<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([TitleComponent, TooltipComponent, LegendComponent, PieChart, CanvasRenderer]);

// 定义props
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  dataItems: {
    type: Array,
    required: true
  },
  completionRate: {
    type: Number,
    required: true
  }
});

// 图表DOM引用
const chartRef = ref(null);
let chart = null;

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 初始化图表
onMounted(() => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value);
    updateChart();
    window.addEventListener('resize', handleResize);
  }
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chart) {
    chart.dispose();
    chart = null;
  }
});

// 监听数据变化，更新图表
watch(() => props.completionRate, updateChart);
watch(() => props.dataItems, updateChart, { deep: true });

// 更新图表
function updateChart() {
  if (!chart) return;
  
  // 从dataItems中获取计划数量和实际产量
  let planQty = 0;
  let actualQty = 0;
  
  props.dataItems.forEach(item => {
    if (item.label === '计划数量 Plan Qty.') {
      planQty = Number(item.value) || 0;
    } else if (item.label === '实际产量 Actual Qty.') {
      actualQty = Number(item.value) || 0;
    }
  });
  
  // 计算完成率
  let completionRate = 0;
  let completedColor = '#4CAF50'; // 绿色
  let uncompletedColor = '#42A5F5'; // 蓝色
  
  if (planQty === 0 && actualQty === 0) {
    // 当计划数量和实际产量都为0时，显示100%蓝色
    completionRate = 0;
    completedColor = '#42A5F5'; // 使用蓝色
    uncompletedColor = '#42A5F5'; // 使用蓝色
  } else if (planQty > 0) {
    completionRate = Math.min(Math.round((actualQty / planQty) * 100), 100);
  } else {
    // 计划数量为0但实际产量不为0的情况，显示100%完成
    completionRate = 100;
  }
  
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        fontSize: 12
      },
      data: ['完成', '未完成']
    },
    series: [
      {
        name: '完成率',
        type: 'pie',
        radius: '70%',
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderWidth: 1,
          borderColor: '#fff'
        },
        label: {
          show: false
        },
        labelLine: {
          show: false
        },
        data: [
          { value: completionRate, name: '完成', itemStyle: { color: completedColor } },
          { value: 100 - completionRate, name: '未完成', itemStyle: { color: uncompletedColor } }
        ]
      }
    ]
  });
}
</script>

<template>
  <div class="plan-chart">
    <div class="plan-content">
      <!-- 左侧：周计划标题和数据 -->
      <div class="left-section">
        <h3 class="plan-title">{{ title }}</h3>
        <div class="data-section">
          <div class="data-row" v-for="(item, index) in dataItems" :key="index">
            <div class="data-label">{{ item.label }}</div>
            <div class="data-value">{{ item.value }}</div>
          </div>
          <!-- 隐藏完成率文字显示行，但保留饼图 -->
          <!-- <div class="completion-rate">
            <div class="rate-label">完成率 Achievement %</div>
            <div class="rate-value">{{ completionRate }}%</div>
          </div> -->
        </div>
      </div>
      
      <!-- 右侧：饼图 -->
      <div class="right-section">
        <div class="chart-container" ref="chartRef"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.plan-chart {
  background-color: #fff;
  border-radius: 6px;
  padding: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 0px;
  width: 100%;
  height: 170px; /* 设置固定高度以节省垂直空间 */
}

.plan-content {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}

.left-section {
  width: 60%;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.right-section {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.plan-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 8px 0;
  border-bottom: 1px solid #eee;
  padding-bottom: 4px;
}

.data-section {
  flex: 1;
  min-width: 0;
}

.data-row {
  display: table;
  width: 100%;
  margin-bottom: 4px;
  font-size: 16px;
}

.data-label, .data-value {
  display: table-cell;
  vertical-align: middle;
}

.data-label {
  font-weight: bold;
  color: #555;
  width: 40%;
}

.data-value {
  font-weight: bold;
  text-align: right;
  width: 60%;
}

.completion-rate {
  display: table;
  width: 100%;
  background-color: #cdcdcd;
  padding: 4px 6px;
  border-radius: 4px;
  margin: 6px 0 0 0;
}

.rate-label, .rate-value {
  display: table-cell;
  vertical-align: middle;
}

.rate-label {
  font-weight: bold;
  font-size: 19px;
  color: #555;
  width: 65%;
}

.rate-value {
  font-weight: bold;
  font-size: 19px;
  color: #4CAF50;
  text-align: right;
  width: 35%;
}

.chart-container {
  width: 100%;
  height: 140px;
  position: relative;
}
</style>